﻿using Newtonsoft.Json;
using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using RXY_Mall.Domain.Rxy;
using RXY_Mall.Services.Finance;
using RXY_Mall.Services.Goods;
using RXY_Mall.Services.Goods.Dto;
using RXY_Mall.Services.Order;
using RXY_Mall.Services.Order.Dto;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RXY_Mall.Services.Order
{
    /// <summary>
    /// 订单服务
    /// </summary>
    public class OrderService : IOrderService
    {
        private RXY_MallContext db;
        private GoodsService goodsService;
        private FinanceService financeService;

        public OrderService()
        {
            db = new RXY_MallContext();
            goodsService = new GoodsService();
            financeService = new FinanceService();
        }

        /// <summary>
        /// 订单是否存在
        /// </summary>
        /// <param name="order_no">订单号</param>
        /// <returns></returns>
        public async Task<bool> IsExistOrder(string order_no)
        {
            var isOrder = await db.gw_orders.AnyAsync(o => o.order_no == order_no && o.deleted == false);
            return isOrder;
        }

        /// <summary>
        /// 是否可以参加拼单
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="order_group_id">拼单ID</param>
        /// <param name="error">错误信息</param>
        /// <returns></returns>
        public bool IsBuyGroup(int user_id, int order_group_id, out string error)
        {
            bool flag = false;
            error = "";

            var orderGroup = db.gw_order_groups
                .Include(g => g.gw_order_group_user)
                .FirstOrDefault(g => g.id == order_group_id);
            if (orderGroup == null || orderGroup.status == (byte)GroupStatus.Failure || orderGroup.status == (byte)GroupStatus.Cancel)
            {
                error = "拼单已结束";
                return flag;
            }

            if (orderGroup.status == (byte)GroupStatus.Succeed)
            {
                error = "拼单已成功";
                return flag;
            }

            if (orderGroup.status == (byte)GroupStatus.Process && orderGroup.expire_time < DateTime.Now)
            {
                error = "拼单已过期";
                return flag;
            }

            if (orderGroup.gw_order_group_user.Any(u => u.user_id == user_id))
            {
                error = "你已参加过拼单";
                return flag;
            }

            if (orderGroup.require_num <= orderGroup.gw_order_group_user.Count)
            {
                error = "人数已满";
                return flag;
            }

            return true;
        }

        /// <summary>
        /// 增加商店和商品销售数量
        /// </summary>
        /// <param name="goods_id"></param>
        /// <param name="goods_count"></param>
        public void AddSaleCount(int goods_id, int goods_count)
        {
            using (RXY_MallContext db = new RXY_MallContext())
            {
                //增加商品销量 商店销量
                var goods = db.gw_goods
                    .Include(g => g.gw_goods_property)
                    .Include(g => g.gw_shop.gw_shop_property)
                    .FirstOrDefault(g => g.id == goods_id);

                //商品销量
                goods.gw_goods_property.sale_count += goods_count;
                goods.gw_shop.gw_shop_property.goods_count += goods_count;
                goods.gw_shop.gw_shop_property.order_count++;
                db.Entry(goods.gw_goods_property).Property(p => p.sale_count).IsModified = true;
                db.Entry(goods.gw_shop.gw_shop_property).Property(p => p.goods_count).IsModified = true;
                db.Entry(goods.gw_shop.gw_shop_property).Property(p => p.order_count).IsModified = true;

                db.SaveChanges();
            }
        }

        /// <summary>
        /// 助力免单
        /// </summary>
        /// <param name="order_group_id">拼单编号</param>
        /// <returns></returns>
        public bool FreeOrder(int order_group_id)
        {
            var flag = false;

            var order = db.gw_orders
                        .Include(o => o.gw_order_goods)
                        .Include(o => o.gw_order_group)
                        .Include(o => o.gw_order_group.gw_order_group_user)
                        .FirstOrDefault(o => o.order_group_id == order_group_id);

            //订单
            if (order == null || order.status != (int)OrderStatus.Group)
            {
                return flag;
            }

            #region 拼单是否成功
            var count = order.gw_order_group.gw_order_group_user.Count(u => u.help_status == 2);
            if (order.gw_order_group != null && order.gw_order_group.require_num <= count && order.gw_order_group.complete_time == null)
            {
                //中奖用户
                var awardUser = order.gw_order_group.gw_order_group_user.ToList()[0];
                if (awardUser == null)
                {
                    return flag;
                }
                awardUser.is_award = true;
                db.Entry(awardUser).Property(o => o.is_award).IsModified = true;

                //修改拼单状态
                order.gw_order_group.status = (byte)GroupStatus.Succeed;
                order.gw_order_group.complete_time = DateTime.Now;
                order.gw_order_group.is_red_packet = true;

                db.Entry(order.gw_order_group).Property(o => o.status).IsModified = true;
                db.Entry(order.gw_order_group).Property(o => o.complete_time).IsModified = true;
                db.Entry(order.gw_order_group).Property(o => o.is_red_packet).IsModified = true;

                order.pay_status = (int)PayStatus.已付款;
                order.status = (int)OrderStatus.Shipment;
                order.group_time = DateTime.Now;
                db.Entry(order).Property(o => o.pay_status).IsModified = true;
                db.Entry(order).Property(o => o.status).IsModified = true;
                db.Entry(order).Property(o => o.group_time).IsModified = true;

                //助力免单成功消息
                //添加订单消息
                gw_message messageOrder = new gw_message()
                {
                    add_time = DateTime.Now,
                    title = "合体免单成功通知",
                    summary = string.Format("恭喜您合体免单成功，获得商品，点击去看看吧~"),
                    content = string.Format("合体免单商品：{0}", order.gw_order_goods.FirstOrDefault().goods_name),
                    picture_url = order.gw_order_goods.FirstOrDefault().picture_url,
                    status = 1,
                    type = (int)MessageType.Order,
                    user_id = order.user_id,
                };
                gw_message_rule_order messageRuleOrder2 = new gw_message_rule_order()
                {
                    order_no = order.order_no,
                    order_status = order.status,
                };
                messageOrder.gw_message_rule_order = messageRuleOrder2;
                db.gw_messages.Add(messageOrder);

                db.SaveChanges();
                flag = true;
            }
            #endregion

            return flag;
        }

        /// <summary>
        /// 红包
        /// </summary>
        /// <param name="number">红包数</param>
        /// <param name="total">红包总额</param>
        /// <param name="min">最小红包</param>
        /// <returns></returns>
        private List<decimal> GetRedpacket(int number, decimal total, decimal min)
        {
            decimal money;
            decimal max;
            int i = 1;
            List<decimal> math = new List<decimal>();
            Random random = new Random();
            while (i < number)
            {
                //保证即使一个红包是最大的了,后面剩下的红包,每个红包也不会小于最小值      
                max = total - min * (number - i);
                int k = (int)(number - i) / 2;
                //保证最后两个人拿的红包不超出剩余红包     
                if (number - i <= 2)
                {
                    k = number - i;
                }
                //最大的红包限定的平均线上下      
                max = max / k;
                //保证每个红包大于最小值,又不会大于最大值      
                money = (int)(min * 100 + ((random.Next(0, 100) / 100.0m) * (max * 100 - min * 100 + 1)));
                money = (decimal)money / 100;
                total = (int)(total * 100 - money * 100);
                total = total / 100;
                math.Add(money);
                i++;
                //最后一个人拿走剩下的红包     
                if (i == number)
                {
                    math.Add(total);
                }
            }
            return math;
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <returns></returns>
        public bool CancelOrder(string order_no, out string error, int user_id = 0)
        {
            bool flag = false;
            error = "";
            try
            {
                var order = db.gw_orders
                    .Include(o => o.gw_order_goods)
                    .Include(o => o.gw_user.gw_finance_property)
                    .FirstOrDefault(o => o.order_no == order_no);

                if (order == null)
                {
                    error = "订单不存在";
                    return flag;
                }

                if (user_id != 0)
                {
                    if (order.user_id != user_id || order.deleted)
                    {
                        error = "订单不存在";
                        return flag;
                    }
                }

                if (order.shipment_status > (byte)ShipmentStatus.已发货)
                {
                    error = "订单已发货";
                    return flag;
                }

                var pay_no = Utils.GetOrderNumber();
                if (order.status == (int)OrderStatus.Pay || order.status == (int)OrderStatus.Shipment)
                {
                    //判断ERP是否可以取消
                    if (!SyncCancelOrder(order.id, out error))
                    {
                        LogHelper.WriteLog(string.Format("订单号:{0},同步取消订单失败,原因:{1}", order.order_no, error));
                        return flag;
                    }


                    //已支付 将钱退回余额
                    if (order.pay_status == (int)PayStatus.已付款 && order.pay_time != null)
                    {
                        //退款
                        if (!RefundOrder(order, pay_no, out error))
                        {
                            LogHelper.WriteLog(string.Format("订单号:{0},退款失败,原因:{1}", order.order_no, error));
                            return flag;
                        }
                        else
                        {
                            LogHelper.WriteLog(string.Format("订单号:{0},退款成功", order.order_no));
                        }

                        var trade_type = TradeType.取消订单退款;

                        order.gw_user.gw_finance_property.balance += order.amount;
                        db.Entry(order.gw_user.gw_finance_property).Property(p => p.balance).IsModified = true;

                        //余额记录
                        var log = new gw_finance_property_log()
                        {
                            add_time = DateTime.Now,
                            order_no = order.order_no,
                            trade_type = (byte)trade_type,
                            currency = (byte)Currencies.Balance,
                            last_value = order.gw_user.gw_finance_property.balance,
                            remark = string.Format("{0},余额增加{1}", trade_type.ToString(), order.amount),
                            type = (int)PaymentType.Income,
                            user_id = order.user_id,
                            value = order.amount,
                        };
                        db.gw_finance_property_logs.Add(log);

                        order.pay_status = (byte)PayStatus.退款;
                        db.Entry(order).Property(o => o.pay_status).IsModified = true;
                    }

                    //foreach (var item in order.gw_order_goods)
                    //{
                    //    //退货
                    //    if (!goodsService.AddSku(item.sku_id, item.quantity, out error))
                    //    {
                    //        LogHelper.WriteLog(string.Format("订单号:{0},商品退库失败,原因:{1}", order.order_no, error));
                    //        return flag;
                    //    }
                    //    else
                    //    {
                    //        LogHelper.WriteLog(string.Format("订单号:{0},商品退库成功", order.order_no));
                    //    }
                    //}


                    //优惠券退回
                    if (order.user_coupon_id > 0)
                    {
                        var coupon = db.gw_user_coupons.Find(order.user_coupon_id);
                        if (coupon != null)
                        {
                            coupon.status = 1;
                            db.Entry(coupon).Property(o => o.status).IsModified = true;
                        }
                    }

                    #region 订单状态
                    //修改订单状态
                    order.status = (int)OrderStatus.Cancel;
                    order.cancel_time = order.pay_expire_time;
                    order.order_status = (byte)OrderStatus2.已取消;

                    db.Entry(order).Property(o => o.status).IsModified = true;
                    db.Entry(order).Property(o => o.cancel_time).IsModified = true;
                    db.Entry(order).Property(o => o.order_status).IsModified = true;
                    #endregion

                    #region 添加消息
                    ////添加订单消息 
                    ////非取消订单
                    //if (user_id == 0)
                    //{
                    //    gw_message messageOrder2 = new gw_message()
                    //    {
                    //        add_time = DateTime.Now,
                    //        title = "订单取消通知",
                    //        summary = "真遗憾，您的订单因30分钟未支付，已为您自动取消~",
                    //        content = string.Format("订单号：{0}\n订单金额：{1}", order.order_no, order.amount),
                    //        picture_url = order.gw_order_goods.FirstOrDefault().picture_url,
                    //        status = 1,
                    //        type = (int)MessageType.Order,
                    //        user_id = order.user_id,
                    //    };
                    //    //添加订单
                    //    gw_message_rule_order messageRuleOrder2 = new gw_message_rule_order()
                    //    {
                    //        order_no = order.order_no,
                    //        order_status = order.status,
                    //    };
                    //    messageOrder2.gw_message_rule_order = messageRuleOrder2;
                    //    db.gw_messages.Add(messageOrder2);
                    //}

                    #endregion

                    db.SaveChanges();
                    flag = true;
                }
                else
                {
                    error = "订单已取消";
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                error = ex.Message;
            }
            return flag;
        }

        /// <summary>
        /// 退款单
        /// </summary>
        /// <param name="order"></param>
        /// <param name="pay_no"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool RefundOrder(gw_order order, string pay_no, out string error)
        {
            error = "";
            var flag = false;
            try
            {
                using (RXY_MallContext db = new RXY_MallContext())
                {
                    var refund = db.gw_order_refunds.Find(order.id);
                    if (refund != null)
                    {
                        error = "订单已退款";
                        return flag;
                    }
                    refund = new gw_order_refund()
                    {
                        add_time = DateTime.Now,
                        pay_no = pay_no,
                        pay_type = order.pay_type,
                        pay_amount = order.amount,
                        id = order.id,
                    };
                    db.gw_order_refunds.Add(refund);
                    db.SaveChanges();
                    flag = true;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                error = "订单已退款";
            }
            return flag;
        }

        /// <summary>
        /// 支付单
        /// </summary>
        /// <param name="order"></param>
        /// <param name="pay_no"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool PayOrder(gw_order order, string pay_no, out string error)
        {
            error = "";
            var flag = false;
            try
            {
                using (RXY_MallContext db = new RXY_MallContext())
                {
                    var payment = db.gw_order_payments.Find(order.id);
                    if (payment != null)
                    {
                        error = "订单已支付";
                        return flag;
                    }

                    payment = new gw_order_payment()
                    {
                        add_time = DateTime.Now,
                        pay_no = pay_no,
                        pay_type = order.pay_type,
                        id = order.id,
                        pay_amount = order.amount,
                    };
                    db.gw_order_payments.Add(payment);
                    db.SaveChanges();
                    flag = true;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                error = "订单已支付";
            }
            return flag;
        }

        /// <summary>
        /// 会员支付单
        /// </summary>
        /// <param name="orderMember"></param>
        /// <param name="pay_no"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool PayMemberOrder(gw_order_member orderMember, string pay_no, out string error)
        {
            error = "";
            var flag = false;
            try
            {
                using (RXY_MallContext db = new RXY_MallContext())
                {
                    var payment = db.gw_order_member_payments.Find(orderMember.id);
                    if (payment != null)
                    {
                        error = "订单已支付";
                        return flag;
                    }

                    payment = new gw_order_member_payment()
                    {
                        add_time = DateTime.Now,
                        pay_no = pay_no,
                        pay_type = orderMember.pay_type,
                        pay_amount = orderMember.amount,
                        id = orderMember.id,
                    };
                    db.gw_order_member_payments.Add(payment);
                    db.SaveChanges();
                    flag = true;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                error = ex.Message;
            }
            return flag;
        }

        /// <summary>
        /// 拆单
        /// </summary>
        /// <param name="order_id">订单号</param>
        /// <returns></returns>
        public string SeparateOrder(int order_id)
        {
            StringBuilder sb_order_no = new StringBuilder();
            try
            {
                //原订单
                var order = db.gw_orders
                   .Include(o => o.gw_order_goods)
                   .Include(o => o.gw_order_address)
                   .FirstOrDefault(o => o.id == order_id);
                sb_order_no.Append(order.order_no);
                //店铺
                var shop_ids = order.gw_order_goods.GroupBy(g => g.shop_id).Select(g => g.Key).ToList();
                if (shop_ids.Count > 1)
                {
                    sb_order_no.Append("-");
                    var count = 0;
                    foreach (var shop_id in shop_ids)
                    {
                        count++;
                        var shop_goods = order.gw_order_goods.Where(g => g.shop_id == shop_id).ToList();

                        List<gw_order_goods> order_goods = new List<gw_order_goods>();
                        int quantity = 0;
                        decimal goods_total = 0m;
                        foreach (var goods in shop_goods)
                        {
                            order_goods.Add(new gw_order_goods()
                            {
                                picture_url = goods.picture_url,
                                pay_price = goods.pay_price,
                                quantity = goods.quantity,
                                goods_id = goods.goods_id,
                                goods_name = goods.goods_name,
                                goods_type = goods.goods_type,
                                category_id = goods.category_id,
                                buy_type = goods.buy_type,
                                settlement_price = goods.settlement_price,
                                shop_id = goods.shop_id,
                                sku_id = goods.sku_id,
                                sku_specs = goods.sku_specs,
                                service_rate = goods.service_rate,
                                volume = goods.volume,
                                weight = goods.weight,
                                api_unit = goods.api_unit,
                                api_goods_id = goods.api_goods_id,
                                is_largess = "N",
                                conversion_rate = goods.conversion_rate,
                            });

                            goods_total += goods.quantity * goods.pay_price;
                            quantity += goods.quantity;
                        }

                        //添加订单
                        var order_no = string.Format("{0}{1}", order.order_no, count.ToString("000"));
                        var new_order = new gw_order()
                        {
                            shop_id = shop_id,
                            parent_id = order.id,
                            order_no = order_no,
                            add_time = DateTime.Now,
                            beans = 0,
                            discounts = 0,
                            goods_count = quantity,
                            status = (byte)OrderStatus.Shipment,
                            user_id = order.user_id,
                            pay_type = order.pay_type,
                            pay_expire_time = order.pay_expire_time,
                            order_status = order.order_status,
                            pay_status = order.pay_status,
                            pay_no = order.pay_no,
                            pay_time = order.pay_time,
                            shipment_status = order.shipment_status,
                            remark = order.remark,
                            goods_total = goods_total,
                            company_id = order.company_id,
                            sync_status = order.sync_status,
                        };

                        new_order.amount = new_order.goods_total;
                        if (order.amount < 0)
                        {
                            order.amount = 0;
                        }
                        new_order.gw_order_goods = order_goods;

                        //添加地址
                        var order_address = new gw_order_address()
                        {
                            accepter_name = order.gw_order_address.accepter_name,
                            address = order.gw_order_address.address,
                            address_id = order.gw_order_address.id,
                            area = order.gw_order_address.area,
                            city_code = order.gw_order_address.city_code,
                            country_code = order.gw_order_address.country_code,
                            email = order.gw_order_address.email,
                            mobile = order.gw_order_address.mobile,
                            post_code = order.gw_order_address.post_code,
                            province_code = order.gw_order_address.province_code,
                            telphone = order.gw_order_address.telphone,
                        };
                        new_order.gw_order_address = order_address;

                        sb_order_no.Append(new_order.order_no);
                        sb_order_no.Append(",");
                        db.gw_orders.Add(new_order);
                    }
                    order.status = (int)OrderStatus.Separate;
                    order.sync_status = null;

                    db.Entry(order).Property(o => o.status).IsModified = true;
                    db.Entry(order).Property(o => o.sync_status).IsModified = true;

                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }

            return sb_order_no.ToString().TrimEnd(',');
        }

        /// <summary>
        /// 发货订单
        /// </summary>
        /// <param name="api_order_no_list"></param>
        /// <returns></returns>
        public async Task<ResponseService<OrderStatusOutput>> ShipmentOrder(List<string> api_order_no_list)
        {
            ResponseService<OrderStatusOutput> result = new ResponseService<OrderStatusOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                List<string> lst = new List<string>();
                foreach (var item in api_order_no_list)
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        lst.Add(item);
                    }
                }

                if (lst.Count == 0)
                {
                    result.msg = "订单号不能为空";
                    return result;
                }

                var orders = await db.gw_orders
                    .Include(o => o.gw_order_goods)
                    .Include(o => o.gw_user.gw_finance_property)
                    .Where(o => lst.Contains(o.api_order_no))
                    .ToListAsync();

                result.data = new OrderStatusOutput();
                result.data.fail_orders = new List<FailOrderOutput>();
                result.data.success_orders = new List<string>();
                result.code = 1;
                foreach (var order in orders)
                {
                    if (order.status == (byte)OrderStatus.Receive)
                    {
                        result.data.success_orders.Add(order.api_order_no);
                        continue;
                    }

                    if (order.status == (int)OrderStatus.Shipment)
                    {
                        try
                        {
                            order.status = (int)OrderStatus.Receive;
                            order.shipment_time = DateTime.Now;
                            order.order_status = (byte)OrderStatus2.处理中;
                            order.shipment_status = (byte)ShipmentStatus.已发货;

                            db.Entry(order).Property(o => o.status).IsModified = true;
                            db.Entry(order).Property(o => o.receive_time).IsModified = true;
                            db.Entry(order).Property(o => o.order_status).IsModified = true;
                            db.Entry(order).Property(o => o.shipment_status).IsModified = true;

                            #region 消息
                            gw_message messageOrder2 = new gw_message()
                            {
                                add_time = DateTime.Now,
                                title = "订单发货通知",
                                summary = "您的商品已发货，请注意查收。",
                                content = string.Format("订单号：{0}\n订单金额：{1}", order.order_no, order.amount),
                                picture_url = order.gw_order_goods.FirstOrDefault().picture_url,
                                status = 1,
                                type = (int)MessageType.Order,
                                user_id = order.user_id,
                            };
                            //添加订单
                            gw_message_rule_order messageRuleOrder2 = new gw_message_rule_order()
                            {
                                order_no = order.order_no,
                                order_status = order.status,
                            };
                            messageOrder2.gw_message_rule_order = messageRuleOrder2;
                            db.gw_messages.Add(messageOrder2);
                            #endregion

                            await db.SaveChangesAsync();
                            result.data.success_orders.Add(order.api_order_no);
                        }
                        catch (Exception ex)
                        {
                            result.data.fail_orders.Add(new FailOrderOutput() { api_order_no = order.api_order_no, reason = ex.Message });
                            LogHelper.WriteLog(ex);
                        }
                    }
                    else
                    {
                        result.data.fail_orders.Add(new FailOrderOutput() { api_order_no = order.api_order_no, reason = "订单状态不正确" });
                    }
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 完成订单
        /// </summary>
        /// <param name="api_order_no_list"></param>
        /// <returns></returns>
        public async Task<ResponseService<OrderStatusOutput>> ReceiveOrder(List<string> api_order_no_list)
        {
            ResponseService<OrderStatusOutput> result = new ResponseService<OrderStatusOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                List<string> lst = new List<string>();
                foreach (var item in api_order_no_list)
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        lst.Add(item);
                    }
                }

                if (lst.Count == 0)
                {
                    result.msg = "订单号不能为空";
                    return result;
                }

                var orders = await db.gw_orders
                    .Include(o => o.gw_order_goods)
                    .Include(o => o.gw_user.gw_finance_property)
                    .Where(o => lst.Contains(o.api_order_no))
                    .ToListAsync();

                result.data = new OrderStatusOutput();
                result.data.fail_orders = new List<FailOrderOutput>();
                result.data.success_orders = new List<string>();
                result.code = 1;
                foreach (var order in orders)
                {
                    if (order.status == (byte)OrderStatus.Complete)
                    {
                        result.data.success_orders.Add(order.api_order_no);
                        continue;
                    }

                    if (order.status == (int)OrderStatus.Shipment || order.status == (int)OrderStatus.Receive)
                    {
                        try
                        {
                            if (order.status == (int)OrderStatus.Shipment)
                            {
                                order.shipment_time = DateTime.Now;
                                db.Entry(order).Property(o => o.shipment_time).IsModified = true;
                            }

                            order.status = (int)OrderStatus.Complete;
                            order.receive_time = DateTime.Now;
                            order.order_status = (byte)OrderStatus2.已完成;
                            order.shipment_status = (byte)ShipmentStatus.已交货;
                            order.service_status = (byte)ServiceStatus.可申请售后;
                            order.service_expire_time = DateTime.Now.AddDays(7);

                            db.Entry(order).Property(o => o.status).IsModified = true;
                            db.Entry(order).Property(o => o.receive_time).IsModified = true;
                            db.Entry(order).Property(o => o.order_status).IsModified = true;
                            db.Entry(order).Property(o => o.shipment_status).IsModified = true;
                            db.Entry(order).Property(o => o.service_status).IsModified = true;
                            db.Entry(order).Property(o => o.service_expire_time).IsModified = true;

                            #region 消息
                            gw_message messageOrder2 = new gw_message()
                            {
                                add_time = DateTime.Now,
                                title = "订单收货通知",
                                summary = "您的商品已签收，请检查商品是否完好，谢谢下次购买。",
                                content = string.Format("订单号：{0}\n订单金额：{1}", order.order_no, order.amount),
                                picture_url = order.gw_order_goods.FirstOrDefault().picture_url,
                                status = 1,
                                type = (int)MessageType.Order,
                                user_id = order.user_id,
                            };
                            //添加订单
                            gw_message_rule_order messageRuleOrder2 = new gw_message_rule_order()
                            {
                                order_no = order.order_no,
                                order_status = order.status,
                            };
                            messageOrder2.gw_message_rule_order = messageRuleOrder2;
                            db.gw_messages.Add(messageOrder2);
                            #endregion

                            await db.SaveChangesAsync();
                            result.data.success_orders.Add(order.order_no);
                        }
                        catch (Exception ex)
                        {
                            result.data.fail_orders.Add(new FailOrderOutput() { api_order_no = order.api_order_no, reason = ex.Message });
                            LogHelper.WriteLog(ex);
                        }
                    }
                    else
                    {
                        result.data.fail_orders.Add(new FailOrderOutput() { api_order_no = order.api_order_no, reason = "订单状态不正确" });
                    }
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;

        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="api_order_no_list"></param>
        /// <returns></returns>
        public async Task<ResponseService<OrderStatusOutput>> CancelOrder(List<string> api_order_no_list)
        {
            ResponseService<OrderStatusOutput> result = new ResponseService<OrderStatusOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                List<string> lst = new List<string>();
                foreach (var item in api_order_no_list)
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        lst.Add(item);
                    }
                }

                if (lst.Count == 0)
                {
                    result.msg = "订单号不能为空";
                    return result;
                }

                var orders = await db.gw_orders
                    .Include(o => o.gw_order_goods)
                    .Include(o => o.gw_user.gw_finance_property)
                    .Where(o => lst.Contains(o.api_order_no))
                    .ToListAsync();

                result.data = new OrderStatusOutput();
                result.data.fail_orders = new List<FailOrderOutput>();
                result.data.success_orders = new List<string>();
                result.code = 1;
                foreach (var order in orders)
                {
                    if (order.status == (byte)OrderStatus.Cancel)
                    {
                        result.data.success_orders.Add(order.api_order_no);
                        continue;
                    }

                    var error = "";
                    var pay_no = Utils.GetOrderNumber();
                    if (order.status == (int)OrderStatus.Pay || order.status == (int)OrderStatus.Shipment)
                    {
                        try
                        {
                            //已支付 将钱退回余额
                            if (order.pay_status == (int)PayStatus.已付款 && order.pay_time != null)
                            {
                                //退款
                                if (!RefundOrder(order, pay_no, out error))
                                {
                                    LogHelper.WriteLog(string.Format("订单号:{0},退款失败,原因:{1}", order.order_no, error));
                                    continue;
                                }
                                else
                                {
                                    LogHelper.WriteLog(string.Format("订单号:{0},退款成功", order.order_no));
                                }

                                var trade_type = TradeType.取消订单退款;

                                order.gw_user.gw_finance_property.balance += order.amount;
                                db.Entry(order.gw_user.gw_finance_property).Property(p => p.balance).IsModified = true;

                                //余额记录
                                var log = new gw_finance_property_log()
                                {
                                    add_time = DateTime.Now,
                                    order_no = order.order_no,
                                    trade_type = (byte)trade_type,
                                    currency = (byte)Currencies.Balance,
                                    last_value = order.gw_user.gw_finance_property.balance,
                                    remark = string.Format("{0},余额增加{1}", trade_type.ToString(), order.amount),
                                    type = (int)PaymentType.Income,
                                    user_id = order.user_id,
                                    value = order.amount,
                                };
                                db.gw_finance_property_logs.Add(log);

                                order.pay_status = (byte)PayStatus.退款;
                                db.Entry(order).Property(o => o.pay_status).IsModified = true;
                            }

                            #region 库存
                            //foreach (var item in order.gw_order_goods)
                            //{
                            //    //退货
                            //    if (!goodsService.AddSku(item.sku_id, item.quantity, out error))
                            //    {
                            //        LogHelper.WriteLog(string.Format("订单号:{0},商品退库失败,原因:{1}", order.order_no, error));
                            //        return flag;
                            //    }
                            //    else
                            //    {
                            //        LogHelper.WriteLog(string.Format("订单号:{0},商品退库成功", order.order_no));
                            //    }
                            //}
                            #endregion

                            //优惠券退回
                            if (order.user_coupon_id > 0)
                            {
                                var coupon = db.gw_user_coupons.Find(order.user_coupon_id);
                                if (coupon != null)
                                {
                                    coupon.status = 1;
                                    db.Entry(coupon).Property(o => o.status).IsModified = true;
                                }
                            }

                            #region 订单状态
                            //修改订单状态
                            order.status = (int)OrderStatus.Cancel;
                            order.cancel_time = order.pay_expire_time;
                            order.order_status = (byte)OrderStatus2.已取消;

                            db.Entry(order).Property(o => o.status).IsModified = true;
                            db.Entry(order).Property(o => o.cancel_time).IsModified = true;
                            db.Entry(order).Property(o => o.order_status).IsModified = true;
                            #endregion

                            #region 添加消息
                            //添加订单消息 
                            //取消订单
                            gw_message messageOrder2 = new gw_message()
                            {
                                add_time = DateTime.Now,
                                title = "订单取消通知",
                                summary = "ERP后台帮您取消订单~",
                                content = string.Format("订单号：{0}\n订单金额：{1}", order.order_no, order.amount),
                                picture_url = order.gw_order_goods.FirstOrDefault().picture_url,
                                status = 1,
                                type = (int)MessageType.Order,
                                user_id = order.user_id,
                            };
                            //添加订单
                            gw_message_rule_order messageRuleOrder2 = new gw_message_rule_order()
                            {
                                order_no = order.order_no,
                                order_status = order.status,
                            };
                            messageOrder2.gw_message_rule_order = messageRuleOrder2;
                            db.gw_messages.Add(messageOrder2);

                            #endregion

                            db.SaveChanges();

                            result.data.success_orders.Add(order.api_order_no);
                        }
                        catch (Exception ex)
                        {
                            result.data.fail_orders.Add(new FailOrderOutput() { api_order_no = order.api_order_no, reason = ex.Message });
                            LogHelper.WriteLog(ex);
                        }
                    }
                    else
                    {
                        result.data.fail_orders.Add(new FailOrderOutput() { api_order_no = order.api_order_no, reason = "订单状态不正确", });
                    }
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 同步订单
        /// </summary>
        public void SyncAddOrder()
        {
            var date = DateTime.Now.AddDays(-30);

            try
            {
                var orders = db.gw_orders
                .Include(o => o.gw_company)
                .Include(o => o.gw_shop)
                .Include(o => o.gw_user)
                .Include(o => o.gw_user.gw_user_store)
                .Include(o => o.gw_order_address)
                .Include(o => o.gw_order_goods)
                .Where(o => o.sync_status == 0 && o.status == (byte)OrderStatus.Shipment && o.add_time > date)
                 .Take(100)
                .ToList();

                foreach (var item in orders)
                {
                    LogHelper.WriteLog(string.Format("订单号:{0},开始同步", item.order_no));
                    var order = new RxyOrderHeadModel()
                    {
                        api_company_id = item.gw_company.api_company_id,
                        api_shop_id = item.gw_shop.api_shop_id,
                        discounts = item.discounts,
                        order_no = item.order_no,
                        order_status = item.status,
                        pay_amount = item.amount,
                        pay_status = "5",//未付款
                        pay_type = item.pay_type,
                        remark = item.remark,
                        shipping_fee = item.shipping_fee,
                        total_amount = item.goods_total,
                    };

                    if ((PayStatus)item.pay_status == PayStatus.已付款)
                    {
                        order.pay_status = "2";//已付款
                    }

                    var customer = new RxyMallCustomerModel()
                    {
                        address = item.gw_order_address.address,
                        accepter_name = item.gw_order_address.accepter_name,
                        api_company_id = item.gw_company.api_company_id,
                        api_user_id = item.gw_user.api_user_id,
                        area = item.gw_order_address.area,
                        city_code = item.gw_order_address.city_code,
                        country_code = item.gw_order_address.country_code,
                        mobile = item.gw_order_address.mobile,
                        province_code = item.gw_order_address.province_code,
                        store_name = item.gw_user.gw_user_store.name,
                        store_type = item.gw_user.gw_user_store.type,
                    };
                    order.rxyMallCustomerModel = customer;

                    order.rxyMallOrderDetailList = new List<RxyMallOrderDetailModel>();
                    foreach (var _goods in item.gw_order_goods)
                    {
                        var goods = new RxyMallOrderDetailModel()
                        {
                            api_goods_id = _goods.api_goods_id,
                            api_unit = _goods.api_unit,
                            conversion_rate = _goods.conversion_rate,
                            goods_name = _goods.goods_name,
                            is_largess = _goods.is_largess,
                            price = _goods.pay_price,
                            quantity = _goods.quantity,
                            total_amount = _goods.pay_price * _goods.quantity,
                        };
                        var spec = JsonConvert.DeserializeObject<List<SpecDto>>(_goods.sku_specs);

                        goods.unit_name = spec.FirstOrDefault().spec_value;

                        order.rxyMallOrderDetailList.Add(goods);
                    }

                    var requestData = JsonConvert.SerializeObject(order);

                    var result = RxyHttpUtils.TransferSync_Post(item.gw_shop.api_server_id, item.gw_shop.api_shop_id, "rxyMallOrderAcceptServlet", requestData);
                    LogHelper.WriteLog("返回结果:" + result);
                    var resultModel = JsonConvert.DeserializeObject<RxyResultModel>(result);

                    if (resultModel.code == "SUCCESS")
                    {
                        var syncOrderOutput = JsonConvert.DeserializeObject<SyncOrderOutput>(resultModel.result);
                        item.api_order_no = syncOrderOutput.rxyBillNo;
                        item.sync_time = DateTime.Now;
                        item.sync_status = 1;
                        db.Entry(item).Property(o => o.api_order_no).IsModified = true;
                        db.Entry(item).Property(o => o.sync_status).IsModified = true;
                        db.Entry(item).Property(o => o.sync_time).IsModified = true;

                        if (!string.IsNullOrWhiteSpace(syncOrderOutput.rxyCustomerID))
                        {
                            item.gw_user.api_user_id = syncOrderOutput.rxyCustomerID;
                            db.Entry(item.gw_user).Property(o => o.api_user_id).IsModified = true;
                        }

                        db.SaveChanges();

                        LogHelper.WriteLog(string.Format("订单号:{0},结束同步,同步成功！", item.order_no));
                    }
                    else
                    {
                        LogHelper.WriteLog(string.Format("订单号:{0},结束同步，同步失败！", item.order_no));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }

        /// <summary>
        /// 同步取消订单
        /// </summary>
        public void SyncCancelOrder()
        {
            var date = DateTime.Now.AddDays(-30);

            try
            {
                var orders = db.gw_orders
                    .Include(o => o.gw_shop)
                    .Where(o => o.sync_status == 0 && o.status == (byte)OrderStatus.Cancel && o.add_time > date)
                    .Take(100)
                    .ToList();

                foreach (var order in orders)
                {
                    if (string.IsNullOrWhiteSpace(order.api_order_no))
                    {
                        order.sync_status = null;
                        db.Entry(order).Property(o => o.sync_status).IsModified = true;
                        db.SaveChanges();
                        continue;
                    }

                    LogHelper.WriteLog(string.Format("订单号:{0},结束同步，同步取消订单开始！", order.order_no));
                    rxyMallOrderStatus orderStatus = new rxyMallOrderStatus()
                    {
                        rxyMallBillNo = order.api_order_no,
                    };

                    var requestData = JsonConvert.SerializeObject(orderStatus);

                    var result = RxyHttpUtils.TransferSync_Post(order.gw_shop.api_server_id, order.gw_shop.api_shop_id, "rxyMallOrderStatusAcceptServlet", requestData);
                    LogHelper.WriteLog("返回结果:" + result);
                    var resultModel = JsonConvert.DeserializeObject<RxyResultModel>(result);

                    if (resultModel.code == "SUCCESS")
                    {
                        order.sync_time = DateTime.Now;
                        order.sync_status = 1;
                        db.Entry(order).Property(o => o.sync_status).IsModified = true;
                        db.Entry(order).Property(o => o.sync_time).IsModified = true;

                        db.SaveChanges();

                        LogHelper.WriteLog(string.Format("订单号:{0},结束同步,同步取消订单成功！", order.order_no));
                    }
                    else
                    {
                        LogHelper.WriteLog(string.Format("订单号:{0},结束同步，同步取消订单失败！", order.order_no));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }

        /// <summary>
        /// 同步取消订单
        /// </summary>
        public bool SyncCancelOrder(int order_id, out string error)
        {
            bool flag = false;
            error = "";
            try
            {
                var order = db.gw_orders
                    .Include(o => o.gw_shop)
                    .FirstOrDefault(o => o.id == order_id);

                if (string.IsNullOrWhiteSpace(order.api_order_no))
                {
                    order.sync_status = null;
                    db.Entry(order).Property(o => o.sync_status).IsModified = true;
                    db.SaveChanges();
                    return true;
                }

                LogHelper.WriteLog(string.Format("订单号:{0},结束同步，同步取消订单开始！", order.order_no));
                rxyMallOrderStatus orderStatus = new rxyMallOrderStatus()
                {
                    rxyMallBillNo = order.api_order_no,
                };

                var requestData = JsonConvert.SerializeObject(orderStatus);

                var result = RxyHttpUtils.TransferSync_Post(order.gw_shop.api_server_id, order.gw_shop.api_shop_id, "rxyMallOrderStatusAcceptServlet", requestData);
                LogHelper.WriteLog("返回结果:" + result);
                var resultModel = JsonConvert.DeserializeObject<RxyResultModel>(result);

                if (resultModel.code == "SUCCESS")
                {
                    order.sync_time = DateTime.Now;
                    order.sync_status = 1;
                    db.Entry(order).Property(o => o.sync_status).IsModified = true;
                    db.Entry(order).Property(o => o.sync_time).IsModified = true;

                    db.SaveChanges();

                    flag = true;
                    LogHelper.WriteLog(string.Format("订单号:{0},结束同步,同步取消订单成功！", order.order_no));
                }
                else
                {
                    error = resultModel.msg;
                    flag = false;
                    LogHelper.WriteLog(string.Format("订单号:{0},结束同步，同步取消订单失败！", order.order_no));
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                error = ex.Message;
            }
            return flag;
        }
    }
}
